loadfile("lib/status.lua")()
loadfile("lib/turtle_utils.lua")()

function placeBlock()
	if turtle.detectDown() then
		turtle.digDown()
	end
	for i=16,2,-1 do
		if turtle.getItemCount(i) > 0 then
			turtle.select(i)
			turtle.placeDown()
			break
		end
	end
end

function doFill(sizex, sizez)

	startx = statusGetProgData().x
	startz = statusGetProgData().z

	if startx == 0 then
		up(1)
		turtle.turnRight()
		statusGetProgData().x = 1
		startx = 1
		statusGetProgData().z = 1
		startz = 1
		statusSave()
	end

	first = true
	for z=startz, sizez do
		print("z="..tostring(z))
		if not fuelFor(sizex) then
			print("no fuel")
			return
		end
		for x=1, sizex do
			print("x="..tostring(z))
			if first and x < startx then
			else
				first = false
				statusGetProgData().x = x
				statusGetProgData().z = z
				print("Placing a block")
				statusSave()
				placeBlock()
				print("Moving")
				statusSave()
				if x < sizex then
					forward(1)
				end
			end
		end
		if not first then
			if z < sizez then
				if (z % 2) == 0 then
					turtle.turnRight()
					forward(1)
					turtle.turnRight()
				else
					turtle.turnLeft()
					forward(1)
					turtle.turnLeft()
				end
			end
		end
	end
end

arg = {...}
if (arg[1] == nil) or (arg[2] == nil) then
	print("Usage: fill x z\n\tFill an area of x width and z depth in the level below the turtle")
else

	sizex = tonumber(arg[1])
	sizez = tonumber(arg[2])

	if not statusLoad() then
		print("Initializing")
		statusInit('fill')
		statusGetProgData().sizex = sizex
		statusGetProgData().sizez = sizez
		statusGetProgData().x = 0
		statusGetProgData().z = 0
	else
		sizex = statusGetProgData().sizex
		sizez = statusGetProgData().sizez
	end

	doFill(sizex, sizez)

	statusEnd()
end

